package com.yungam.other.mes_controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.yungam.common.bean.process.ProcessEquipment;
import com.yungam.common.bean.process.ProcessInspection;
import com.yungam.common.bean.process.ProductProcess;
import com.yungam.common.bean.product.ProductInfo;
import com.yungam.common.service.ProcessEquipmentService;
import com.yungam.common.service.ProcessInspectionService;
import com.yungam.common.service.ProductInfoService;
import com.yungam.common.service.ProductProcessService;
import com.yungam.other.response.ResData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品信息同步接口
 */
@Slf4j
@RestController
public class SynchronizeProductController {

    @Resource
    private ProductInfoService productInfoService;
    @Resource
    private ProductProcessService productProcessService;
    @Resource
    private ProcessInspectionService processInspectionService;
    @Resource
    private ProcessEquipmentService processEquipmentService;


    @PostMapping("/IMCS/synchronizeProduct")
    public Map<String, Object> synchronizeProduct(@RequestBody Map<String, Object> params) {
        log.info("========= START『mes调用imcs』[产品信息同步接口]=========");
        log.info("=========『mes数据』{}", new Gson().toJson(params));

        //
        Map<Integer, Object> processMapper = new HashMap<>(); // 存放 <processId 其他信息>的键值对
        //
        Long productId = Long.valueOf(params.get("productId").toString());
        String productNo = String.valueOf(params.get("productNo"));
        // product_info 表 先删后插入
        ProductInfo productInfo = productInfoService.getOne(new QueryWrapper<ProductInfo>()
                .eq("product_id", productId).eq("product_no", productNo));
        if (productInfo != null) {
            productInfoService.removeById(productId);
        }
        productInfo = new ProductInfo();
        productInfo.setProductId(productId);
        productInfo.setProductNo(productNo);
        productInfo.setProductName(String.valueOf(params.get("productName")));
        productInfo.setQtyJoin((Integer) params.get("qtyJoin"));
        productInfoService.save(productInfo);

        // 删除 product_process 原有数据
        productProcessService.remove(new QueryWrapper<ProductProcess>()
                .eq("product_id", productId).eq("product_no", productNo));

        // 先将 process_inspection 和 process_equipment 信息存入 map, 等保存完 product_process 获取 process_id 后再统一保存
        List<Map<String, Object>> process = (List<Map<String, Object>>) params.get("process");
        for (Map<String, Object> map : process) {
            // product_process
            ProductProcess pp = new ProductProcess();
            pp.setProductId(productId);
            pp.setProductNo(productNo);
            String processNo = String.valueOf(map.get("processNo"));
            String processName = String.valueOf(map.get("processName"));
            pp.setProcessNo(processNo);
            pp.setProcessName(processName);
            boolean flag = productProcessService.save(pp);
            // 获取 process_id
            if (!flag || pp.getProcessId() == null) {
                log.error("工序: {} {} 插入失败", processNo, processName);
                continue;
            }
            Integer processId = pp.getProcessId();
            Map<String, Object> other = new HashMap<>();
            Object inspectionItems = map.get("inspectionItems");
            Object eqpts = map.get("eqpts");
            other.put("inspectionItems", inspectionItems);
            other.put("eqpts", eqpts);
            processMapper.put(processId, other);
        }

        // 处理表 ProcessInspection 和 process_equipment
        List<ProcessInspection> inspectionList = Lists.newArrayList();
        List<ProcessEquipment> peList = Lists.newArrayList();
        for (Integer cur : processMapper.keySet()) {
            Map<String, Object> item = (Map<String, Object>) processMapper.get(cur);
            List<Map<String, Object>> inspections = (List<Map<String, Object>>) item.get("inspectionItems");
            List<Map<String, Object>> equips= (List<Map<String, Object>>) item.get("eqpts");
            // process_inspection 表
            for (Map<String, Object> ist : inspections) {
                ProcessInspection pi = new ProcessInspection();
                pi.setProcessId(cur);
                pi.setItemCode(String.valueOf(ist.getOrDefault("itemCode", "")));
                pi.setStandardValue(String.valueOf(ist.getOrDefault("standardValue", "")));
                pi.setMaxValue(String.valueOf(ist.getOrDefault("maxValue", "")));
                pi.setMinValue(String.valueOf(ist.getOrDefault("minValue", "")));
                inspectionList.add(pi);
            }
            // process_equipment 表
            for (Map<String, Object> eq : equips) {
                ProcessEquipment pe = new ProcessEquipment();
                pe.setProcessId(cur);
                pe.setEquNumber(String.valueOf(eq.getOrDefault("eqptNo", "")));
                peList.add(pe);
            }
        }
        // 先清空后插入（覆盖）
        List<Integer> ids;
        if (!inspectionList.isEmpty()) {
            log.info("处理表 ProcessInspection");
            ids = inspectionList.stream().map(ProcessInspection::getProcessId).collect(Collectors.toList());
            log.info("先清空ProcessInspection表, 清空的process_id为{}", new Gson().toJson(ids));
            processInspectionService.remove(new QueryWrapper<ProcessInspection>().in("process_id", ids));
            log.info("插入ProcessInspection表, 插入的数据为{}", new Gson().toJson(inspectionList));
            processInspectionService.saveBatch(inspectionList);
        }
        if (!peList.isEmpty()) {
            log.info("处理表 ProcessEquipment");
            ids = peList.stream().map(ProcessEquipment::getProcessId).collect(Collectors.toList());
            log.info("先清空ProcessEquipment, 清空的process_id为{}", new Gson().toJson(ids));
            processEquipmentService.remove(new QueryWrapper<ProcessEquipment>().in("process_id", ids));
            log.info("ProcessEquipment, 插入的数据为{}", new Gson().toJson(peList));
            processEquipmentService.saveBatch(peList);
        }

        log.info("同步成功");
        return ResData.success("产品同步成功");
    }

}
